/*
 * Copyright 2009 Zero Separation
 *
 *     This file is part of PDSUtilities.
 *
 *  PDSUtilities is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  PDSUtilities is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with PDSUtilities.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package com.zero_separation.pds.utilities.referencecollections;

import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ManagedObject;
import com.sun.sgs.app.ManagedReference;
import java.io.Serializable;

/**
 * This base class is used by all of the ReferenceCollection classes in order
 * to process Managed Objects and References correctly.
 *
 * @author Tim Boura - Zero Separation
 */
public abstract class ReferenceAbstract implements Serializable {
    /** The version of the serialized form of this class. */
    private static final long serialVersionUID = 1L;

    /**
     * This method takes an object and checks whether it is a ManagedObject. If
     * it is then it returns a new ManagedReference to that object, if not then
     * it returns the object unchanged.
     *
     * @param ob The object to turn into a reference if needed
     * @return Either the object or a reference to the object
     * @throws IllegalArgumentException If the object was already a managed reference
     */
    protected static Object referenceIfNeeded(Object ob) throws IllegalArgumentException {
        if (ob instanceof ManagedReference)
            throw new IllegalArgumentException("Cannot add a managed reference to a Reference Collection - add the managed object not the reference");
        if (ob instanceof ManagedObject)
            return AppContext.getDataManager().createReference(ob);
        else
            return ob;
    }

    /**
     * This method takes an object and checks whether it is a ManagedReference. If
     * it is then it dereferences it and returns the resulting object. If not then
     * it returns the object unchanged.
     *
     * @param ob The object to dereference if needed
     * @return The object
     */
    protected static Object dereferenceIfNeeded(Object ob) {
        if (ob instanceof ManagedReference)
            return ((ManagedReference)ob).get();
        else
            return ob;
    }
}
